﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace AzureDiagMon.Common.Mvvm
{
    public class CheckableCollection : ObservableCollection<ICheckable>, INotifyPropertyChanged
    {
        public CheckableCollection(IEnumerable items)
            : base(items.Cast<object>().Select(f => (ICheckable)new Checkable(f)))
        {
            foreach (var checkable in Items)
            {
                checkable.PropertyChanged += CheckableItemPropertyChanged;
            }
        }

        private bool internalUpdate = false;

        protected IEnumerable checkedItems;
        public IEnumerable CheckedItems
        {
            get { return checkedItems; }
            set
            {
                internalUpdate = true;
                try
                {
                    checkedItems = value;
                    foreach (var checkedItem in checkedItems)
                    {
                        if (Items != null)
                        {
                            var singleOrDefault = Items.SingleOrDefault(f => f.Entity.Equals(checkedItem));
                            if (singleOrDefault != null)
                                singleOrDefault.IsChecked = true;
                        }
                    }
                }
                finally
                {
                    internalUpdate = false;
                }
                OnPropertyChanged(new PropertyChangedEventArgs("CheckedItems"));
            }
        }

        void CheckableItemPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsChecked")
            {
                if (internalUpdate)
                    return;

                checkedItems = GetCheckedItems();
                OnPropertyChanged(new PropertyChangedEventArgs("CheckedItems"));
            }
        }

        protected IEnumerable GetCheckedItems()
        {
            return Items.Where(f => f.IsEnabled && f.IsChecked)
                .Select(f => f.Entity).ToList();
        }

    }
}
